package com.hc.comm.utils;

import java.util.ArrayList;

import com.hc.comm.base.IPagerService;
import com.hc.comm.base.PagerModel;
import com.hc.comm.dto.DTO;
import com.hc.comm.utils.Constant.DbTypes;
import com.hc.comm.utils.Constant.DbTypes.DbTypeEnum;


/**
 * 分页辅助类
 */
public class PagerUtil {

	/**
	 * 分页大小
	 */
	public static final int pageSize = 20;

	/**
	 * 数据库类型
	 */
	private static final String dbtype = DbTypeEnum.MYSQL.getValue();

	/**
	 * 分页
	 * 
	 * @param pager
	 * @param paramMap
	 * @param dbtype
	 * @return
	 * @throws Exception
	 */
	public static <T> PagerModel<T> getPagerModel(IPagerService<T> pagerService, DTO dto)
			throws Exception {
		PagerModel<T> pagerModel = new PagerModel<T>();
		if (dto == null) {
			ExceptionUtils.throwBaseException("参数异常");
		}
		if (dto.getPage() == null) {
			dto.setPage(1);
		}
		if (dto.getRows() == null || dto.getRows() > 100) {
			dto.setRows(PagerUtil.pageSize);
		}
		dto.setDbtype(dbtype);

		pagerModel.setPageSize(dto.getRows());
		pagerModel.setCurrentPage(dto.getPage());
		pagerModel.setCount(pagerService.queryCount(dto));
		pagerModel.setStartIndex(
				(pagerModel.getCurrentPage() - 1) * pagerModel.getPageSize()
						+ 1);
		pagerModel.setEndIndex(
				pagerModel.getStartIndex() + pagerModel.getPageSize() - 1);
		pagerModel
				.setPageCount(
						(pagerModel.getCount() % pagerModel.getPageSize() == 0)
								? pagerModel.getCount() / pagerModel
										.getPageSize()
								: pagerModel.getCount()
										/ pagerModel.getPageSize() + 1);
		if (pagerModel.getCurrentPage() >= pagerModel.getPageCount()) {
			pagerModel.setCurrentPage(pagerModel.getPageCount());
			pagerModel.setNextPage(pagerModel.getPageCount());
		} else {
			pagerModel.setNextPage(pagerModel.getCurrentPage() + 1);
		}
		if (pagerModel.getPriviousPage() == null
				|| pagerModel.getPriviousPage() <= 1) {
			pagerModel.setPriviousPage(1);
		} else {
			pagerModel.setPriviousPage(pagerModel.getCurrentPage() - 1);
		}

		if (DbTypes.isMysql(dbtype)) {
			if (pagerModel.getStartIndex() <= 0) {
				dto.setRowstartindex(0);
				dto.setRowendindex(0);
			} else {
				dto.setRowstartindex(pagerModel.getStartIndex() - 1);
				dto.setRowendindex(pagerModel.getPageSize());
			}
		} else {
			dto.setRowstartindex(pagerModel.getStartIndex());
			dto.setRowendindex(pagerModel.getEndIndex());
		}
		if (pagerModel.getCount() >= 1) {
			pagerModel.setDataList(pagerService.queryList(dto));
		} else {
			pagerModel.setDataList(new ArrayList<T>());
		}
		return pagerModel;
	}

}
